﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using RN.ERP.BLL;
using RN.ERP.DTO;
using System.Web.Services;
using Newtonsoft.Json;
using RN.ERP.BLL.ZBDLRY;

namespace RN.ERP.Web.Material.Material
{
    public partial class MaterialInfo : BasePage
    {
        MaterialBLL bll = new MaterialBLL();
        BaseBasicBLL bbll = new BasicBLL();

        public string Id
        {
            get
            {
                return hdnId.Value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
            }
        }

        private void InitPage()
        {
            hdnId.Value = Request.QueryString["id"];
            BindMPClassData();
            string optType = Request.QueryString["type"];
            hdnType.Value = optType;
            switch (optType)
            {
                case "1":
                    InitViewMode(true);
                    break;
                case "2":
                    InitViewMode(false);
                    break;
                default:
                    break;
            }
            Dictionary<string, string> unitDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(bbll.GetDictionary("RN_MATE_UNIT", "", ""));
            ddlUnit.DataSource = unitDic;
            ddlUnit.DataTextField = "value";
            ddlUnit.DataValueField = "key";
            ddlUnit.DataBind();
        }

        private void InitViewMode(bool isLock)
        {
            string mpId = hdnId.Value;
            int id = 0;
            if (int.TryParse(mpId, out id))
            {
                DTO.Material property = bll.GetMaterial(id);
                hdnCode.Value = property.cMCode;
                txtName.Text = property.cMName;
                txtMNum.Text = property.iMNum.ToString();
                txtClass.Text = property.cMCName;
                txtMEval.Text = property.dMEvaluate.ToString();
                foreach (ListItem item in ddlUnit.Items)
                {
                    if (item.Value == property.cUnit)
                    {
                        item.Selected = true;
                        break;
                    }
                }
                if (property.bIsAssets)
                {
                    cbInfo.Items[0].Selected = true;
                }
                if (property.bIsBorrow)
                {
                    cbInfo.Items[1].Selected = true;
                }
                if (property.bIsSale)
                {
                    cbInfo.Items[2].Selected = true;
                }
                if (property.bIsSample)
                {
                    cbInfo.Items[3].Selected = true;
                }
                txtAreMemo.Text = property.cMemo;
                int count1 = 0;
                List<DTO.MateProperty> paaa = bll.GetMaterialProperties(
                    0,
                    0,
                    out count1);
                paaa.Insert(0, new DTO.MateProperty() { id = 0, cMPName = "--请选择--" });
                int pcId = 0;
                int.TryParse(property.cMPCode, out pcId);
                var ps = paaa.SingleOrDefault(p => p.id == pcId);
                if (ps != null)
                {
                    ddlMPClass.SelectedIndex = paaa.IndexOf(ps);
                }

                int pid = 0;
                if (int.TryParse(ddlMPClass.SelectedValue, out pid))
                {
                    int count = 0;
                    List<DTO.MPInfo> properties = bll.GetMPListByPropertyId(
                        pid,
                        0,
                        0,
                        out count);
                    rptMPInfo.DataSource = properties;
                    rptMPInfo.DataBind();
                }
                foreach (RepeaterItem item in rptMPInfo.Items)
                {
                    HiddenField hdn = item.FindControl("hdniMPIKind") as HiddenField;
                    HiddenField hdn2 = item.FindControl("hdncMPIInfo") as HiddenField;
                    HiddenField hdn3 = item.FindControl("hdnCode") as HiddenField;
                    TextBox txt1 = item.FindControl("txtSingle") as TextBox;
                    TextBox txt2 = item.FindControl("txtMulti") as TextBox;
                    DropDownList ddl = item.FindControl("ddlSelect") as DropDownList;
                    CheckBoxList cb = item.FindControl("cbSelect") as CheckBoxList;
                    DTO.MInfo m = property.Minfos.LastOrDefault(mi => mi.cMPICode == hdn3.Value);
                    switch (hdn.Value.Trim())
                    {
                        case "1":
                            ddl.SelectedValue = m.cMPIText;
                            break;
                        case "2":
                            string[] s = m.cMPIText.Split(new char[] { '!', '#' });
                            for (int i = 0; i < cb.Items.Count; i++)
                            {
                                if (s.Contains(cb.Items[i].Value))
                                {
                                    cb.Items[i].Selected = true;
                                }
                            }
                            break;
                        case "3":
                            txt1.Text = m.cMPIText;
                            break;
                        case "4":
                            txt2.Text = m.cMPIText;
                            break;
                    }
                }
                ddlMPClass.Enabled = false;

                if (isLock)
                {
                    txtName.Enabled = false;
                    txtMNum.Enabled = false;
                    txtMEval.Enabled = false;
                    cbInfo.Enabled = false;
                    txtAreMemo.Enabled = false;
                    foreach (RepeaterItem item in rptMPInfo.Items)
                    {
                        foreach (Control control in item.Controls)
                        {
                            if (control is WebControl)
                            {
                                ((WebControl)control).Enabled = false;
                            }
                        }
                    }
                    LinkButton1.Visible = false;
                    dv1.Visible = false;
                    ddlUnit.Enabled = false;
                }
            }
        }

        private void BindMPClassData()
        {
            int count = 0;
            List<DTO.MateProperty> properties = bll.GetMaterialProperties(
                0,
                0,
                out count);
            properties.Insert(0, new DTO.MateProperty() { id = 0, cMPName = "--请选择--" });
            ddlMPClass.DataSource = properties;
            ddlMPClass.DataValueField = "id";
            ddlMPClass.DataTextField = "cMPName";
            ddlMPClass.DataBind();
        }

        protected void rptMPInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                HiddenField hdn = e.Item.FindControl("hdniMPIKind") as HiddenField;
                HiddenField hdn2 = e.Item.FindControl("hdncMPIInfo") as HiddenField;
                TextBox txt1 = e.Item.FindControl("txtSingle") as TextBox;
                TextBox txt2 = e.Item.FindControl("txtMulti") as TextBox;
                DropDownList ddl = e.Item.FindControl("ddlSelect") as DropDownList;
                CheckBoxList cb = e.Item.FindControl("cbSelect") as CheckBoxList;
                if (hdn != null)
                {
                    switch (hdn.Value.Trim())
                    {
                        case "1":
                            ddl.Visible = true;
                            if (!string.IsNullOrEmpty(hdn2.Value))
                            {
                                string[] s = hdn2.Value.Split(new char[] { '!', '#' }, StringSplitOptions.RemoveEmptyEntries);
                                ddl.DataSource = s;
                                ddl.DataBind();
                            }
                            break;
                        case "2":
                            cb.Visible = true;
                            if (!string.IsNullOrEmpty(hdn2.Value))
                            {
                                string[] s = hdn2.Value.Split(new char[] { '!', '#' }, StringSplitOptions.RemoveEmptyEntries);
                                cb.DataSource = s;
                                cb.DataBind();
                            }
                            break;
                        case "3":
                            txt1.Visible = true;
                            break;
                        case "4":
                            txt2.Visible = true;
                            break;
                        default:
                            break;

                    }
                }
            }
        }

        protected void ddlMPClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            int pid = 0;
            if (int.TryParse(ddlMPClass.SelectedValue, out pid))
            {
                int count = 0;
                List<DTO.MPInfo> properties = bll.GetMPListByPropertyId(
                    pid,
                    0,
                    0,
                    out count);
                rptMPInfo.DataSource = properties;
                rptMPInfo.DataBind();
            }
        }

        protected void lbtnSave_Click(object sender, EventArgs e)
        {
            DTO.Material material = new DTO.Material();
            List<DTO.MInfo> minfos = new List<MInfo>();
            InitData(out material, out minfos);
            DTO.OperationResult r1 = new OperationResult();
            switch (hdnType.Value)
            {
                case "0":
                    r1 = bll.AddMaterial(material);
                    break;
                case "2":
                    int mpid = 0;
                    int.TryParse(hdnId.Value.Trim(), out mpid);
                    material.id = mpid;
                    r1 = bll.EdtiMaterial(material);
                    break;
                default:
                    break;
            }
            if (r1.Result)
            {
                string code = r1.ReturnValue.ToString();
                DTO.OperationResult r2 = bll.SaveMInfo(minfos, code, UserInfo.CorpUserGuid);
                if (r2.Result)
                {
                    LinkButton1.Enabled = false;
                }
                UtilitiesTool.LigerAlert(this, r2.Message);
            }
            else
            {
                UtilitiesTool.LigerAlert(this, r1.Message);
            }
        }

        private void InitData(out DTO.Material material, out List<DTO.MInfo> minfos)
        {
            material = new DTO.Material();
            minfos = new List<MInfo>();

            #region 封装Material

            material.iStatus = 0;
            material.cPicURL = Guid.NewGuid().ToString();
            material.cUnit = ddlUnit.SelectedValue;
            if (!string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                material.cMName = txtName.Text.Trim();
            }
            else
            {
                UtilitiesTool.LigerAlert(this, "请填写物资名称！");
            }
            if (!string.IsNullOrEmpty(hdnMCCode.Value.Trim()))
            {
                material.cMCCode = hdnMCCode.Value.Trim();
            }
            else
            {
                UtilitiesTool.LigerAlert(this, "请选择物资分类！");
            }
            int num = 0;
            if (int.TryParse(txtMNum.Text.Trim(), out num))
            {
                material.iMNum = num;
            }
            else
            {
                UtilitiesTool.LigerAlert(this, "物资数量格式不正确！");
            }
            decimal ev = 0;
            if (decimal.TryParse(txtMEval.Text.Trim(), out ev))
            {
                material.dMEvaluate = ev;
            }
            else
            {
                UtilitiesTool.LigerAlert(this, "物资估算单价格式不正确！");
            }
            if (cbInfo.Items[0].Selected)
            {
                material.bIsAssets = true;
            }
            if (cbInfo.Items[1].Selected)
            {
                material.bIsBorrow = true;
            }
            if (cbInfo.Items[2].Selected)
            {
                material.bIsSale = true;
            }
            if (cbInfo.Items[3].Selected)
            {
                material.bIsSample = true;
            }
            material.cMemo = txtAreMemo.Text.Trim();
            if (ddlMPClass.SelectedValue != "0")
            {
                material.cMPCode = ddlMPClass.SelectedValue;
            }
            else
            {
                UtilitiesTool.LigerAlert(this, "请选择物资属性类型！");
            }
            material.cCUid = UserInfo.CorpUserGuid;

            #endregion

            #region 封装minfo

            foreach (RepeaterItem item in rptMPInfo.Items)
            {
                DTO.MInfo m = new MInfo();
                HiddenField hdn = item.FindControl("hdniMPIKind") as HiddenField;
                HiddenField hdn2 = item.FindControl("hdncMPIInfo") as HiddenField;
                HiddenField hdn3 = item.FindControl("hdnCode") as HiddenField;
                TextBox txt1 = item.FindControl("txtSingle") as TextBox;
                TextBox txt2 = item.FindControl("txtMulti") as TextBox;
                DropDownList ddl = item.FindControl("ddlSelect") as DropDownList;
                CheckBoxList cb = item.FindControl("cbSelect") as CheckBoxList;
                m.cMPICode = hdn3.Value;
                m.cMCode = hdnCode.Value;
                switch (hdn.Value.Trim())
                {
                    case "1":
                        m.cMPIText = ddl.SelectedValue;
                        break;
                    case "2":
                        string selectValue = string.Empty;
                        for (int i = 0; i < cb.Items.Count; i++)
                        {
                            if (cb.Items[i].Selected)
                            {
                                selectValue += cb.Items[i].Value + "!#";
                            }
                        }
                        selectValue = selectValue.TrimEnd(new char[] { '!', '#' });
                        m.cMPIText = selectValue;
                        break;
                    case "3":
                        m.cMPIText = txt1.Text.Trim();
                        break;
                    case "4":
                        m.cMPIText = txt2.Text.Trim();
                        break;
                }
                minfos.Add(m);
            }

            #endregion
        }
    }
}